package com.hst.cz.cameralib;

import android.content.Context;
import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.util.AttributeSet;
import android.util.Log;

public class WlCameraView extends WLEGLSurfaceView{

    private final WlCamera mWCamera;//摄像头的控制类
    private ICallback callback;
    private boolean isCreated = false;

    private final int mCameraId = 0;//摄像头ID
    private final int mWidth = 768;//渲染的宽
    private final int mHeight = 400;//渲染的高

    public WlCameraView(Context context) {
        this(context, null);
    }

    public WlCameraView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public WlCameraView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        //摄像头纹理渲染器

        WlCameraRender mWlCameraRender = new WlCameraRender(context,mWidth,mHeight);
        mWCamera = new WlCamera();
        setRender(mWlCameraRender);

        mWlCameraRender.setOnSurfaceCreateListener(new WlCameraRender.OnSurfaceCreateListener() {
            @Override
            public void onSurfaceCreate(SurfaceTexture surfaceTexture) {
                //在View创建后，初始化及打开摄像头
                try {
                    Camera mCamera = mWCamera.initCamera(surfaceTexture, mCameraId);
                    mCamera.setErrorCallback(mCameraError);
                    isCreated = true;
                    if (callback != null){
                        callback.onCameraViewCreated();
                    }

                }catch (Exception e){
                    e.printStackTrace();
                    if (callback != null){
                        callback.onCameraViewError(e);
                    }
                }

            }
        });
    }

    public void setCallback(ICallback callback){
        this.callback = callback;
        if (isCreated&&callback != null){
            callback.onCameraViewCreated();
        }
    }

    private final Camera.ErrorCallback mCameraError = new Camera.ErrorCallback() {
        @Override
        public void onError(int error, Camera camera) {
            //当摄像头被其他进程占用时会回调
            if (callback != null){
                callback.onCameraViewError(new RuntimeException("Camera Error Code:"+error));
            }
        }
    };

    public void stopCamera()
    {
        if(mWCamera != null)
        {
            try {
                mWCamera.stopPreview();
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        onSurfaceDestroyed();
    }


    @Override
    public void onSurfaceDestroyed() {
        super.onSurfaceDestroyed();

        if (callback != null){
            callback.onCameraViewDestroyed();
        }
    }

    public interface ICallback{
        void onCameraViewCreated();
        void onCameraViewDestroyed();
        void onCameraViewError(Exception e);
    }
}